package cn.dgut.training.service.impl;

import cn.dgut.training.annotation.LoginUser;
import cn.dgut.training.dto.activity.CouponDTO;
import cn.dgut.training.dto.activity.CouponUserDTO;
import cn.dgut.training.entity.activity.Coupon;
import cn.dgut.training.entity.activity.CouponUser;
import cn.dgut.training.entity.activity.GroupBuying;
import cn.dgut.training.mapper.CouponMapper;
import cn.dgut.training.mapper.CouponUserMapper;
import cn.dgut.training.service.ICouponService;
import cn.dgut.training.utils.UUIDUtil;
import cn.dgut.training.vo.BaseVO;
import cn.dgut.training.vo.CommonResponse;
import cn.dgut.training.vo.activity.CouponFrontVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Resource
    private CouponMapper couponMapper;

    @Resource
    private CouponUserMapper couponUserMapper;

    /**
     * 添加优惠券
     * @param coupon
     * @return
     */
    @Transactional
    public CommonResponse add(Coupon coupon){
        if(coupon.getCouponType()==2){
            coupon.setCode(UUIDUtil.generateShortUuid());
        }
        couponMapper.insert(coupon);
        return CommonResponse.success(coupon);
    }

    public BaseVO listCouponByPage(CouponDTO couponDTO){

        //构造分页
        IPage page=new Page();
        BeanUtils.copyProperties(couponDTO,page);
        //获取条件查询构造器
        QueryWrapper queryWrapper=CouponDTO.getWrapper(couponDTO);

        IPage res=couponMapper.selectPage(page,queryWrapper);

        BaseVO baseVO=new BaseVO(res);

        return baseVO;
    }


    /**
     * 根据兑换码查询优惠券
     */
    public Coupon getCoupunByCode(String code) {

        QueryWrapper<Coupon> queryWrapper=new QueryWrapper();

        queryWrapper.lambda().eq(Coupon::getCode,code);

        Coupon coupon=couponMapper.selectOne(queryWrapper);

        return coupon;

    }

    public  List<CouponFrontVO> selectCouponsByOrder(Long userId, Long cartId, Long grouponRulesId){


        //调用购物车接口查询当前用户的购物车列表

        //据用户id查找用户优惠券表并且封装成CouponFrontVO
        QueryWrapper queryWrapper= CouponUserDTO.getWrapperByUserId(userId);
        List<CouponUser> couponUserList=couponUserMapper.selectList(queryWrapper);
        List<CouponFrontVO> couponVOList=change(couponUserList);


        return couponVOList;
    }

    /**
     * List<CouponUser>查询当前Coupon转List<CouponFrontVO>
     * @param couponUsers
     * @return
     */
    public List<CouponFrontVO> change(List<CouponUser> couponUsers){

        List<CouponFrontVO> couponFrontVOS=new ArrayList<>();
        for (CouponUser c:couponUsers) {
            CouponFrontVO temp=new CouponFrontVO();
            BeanUtils.copyProperties(c,temp);
            Coupon coupon=couponMapper.selectById(c.getCouponId());
            BeanUtils.copyProperties(coupon,temp);
            temp.setAvailable(checkCoupon(coupon.getId(),c.getId(),new BigDecimal(200.0)));
            couponFrontVOS.add(temp);
        }
        return couponFrontVOS;
    }

    /**
     *@Description  检查当前优惠券是否可用
     *@Param  [userId, couponId, userCouponId, checkedGoodsPrice]
     *@Return  boolean
     *@创建人  刘祝蓝
     *@创建时间  2019/12/28 16:14
     */
    public boolean checkCoupon(Long couponId, Long userCouponId, BigDecimal checkedGoodsPrice){

        Coupon coupon=couponMapper.selectById(couponId);
        if (coupon==null){
            return false;
        }
        //检查商品是否符合(是否是全类目，如果有商品，那么是全部商品，哪些分类或者哪些商品）

        //检查优惠券使用状态
        CouponUser couponUser=couponUserMapper.selectById(userCouponId);
        if(couponUser==null){
            return false;
        }
        //检查是否满足最低消费
        couponMapper.selectById(couponId);
        if(checkedGoodsPrice.compareTo(coupon.getCouponMin())==-1){
            return false;
        }
        //检查是否过期
        Date now = new Date();

        //1.当前日期超出使用时间
        if(coupon.getDays()==0){
            if((now.before(coupon.getStartTime())||now.after(coupon.getEndTime()))){
                return false;
            }
        }else {
            //2.天数超过
            if(now.getTime()>couponUser.getAddTime().getTime()+coupon.getDays()*24*60*60*1000){
                return false;
            }
        }

        return true;
    }

}
